{% extends "base.html" %}

{% block title %}策略管理 - XCQuant{% endblock %}

{% block breadcrumb %}
<nav aria-label="breadcrumb">
    <ol class="breadcrumb">
        <li class="breadcrumb-item"><a href="{{ url_for('index') }}">首页</a></li>
        <li class="breadcrumb-item active">策略管理</li>
    </ol>
</nav>
{% endblock %}

{% block content %}
<!-- 页面标题 -->
<div class="d-flex justify-content-between align-items-center mb-4">
    <h1 class="h3 mb-0 text-gray-800">
        <i class="fas fa-cogs me-2"></i>策略管理
    </h1>
    <div>
        <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#createStrategyModal">
            <i class="fas fa-plus me-2"></i>创建策略
        </button>
    </div>
</div>

<!-- 策略列表 -->
<div class="row">
    <div class="col-lg-8">
        <div class="card shadow mb-4">
            <div class="card-header py-3">
                <h6 class="m-0 font-weight-bold text-primary">
                    <i class="fas fa-list me-2"></i>策略列表
                </h6>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-bordered" id="strategiesTable">
                        <thead>
                            <tr>
                                <th>策略名称</th>
                                <th>类型</th>
                                <th>交易对</th>
                                <th>状态</th>
                                <th>收益率</th>
                                <th>创建时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="strategiesBody">
                            <tr>
                                <td colspan="7" class="text-center text-muted">
                                    <i class="fas fa-spinner fa-spin me-2"></i>加载中...
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 策略统计 -->
    <div class="col-lg-4">
        <div class="card shadow mb-4">
            <div class="card-header py-3">
                <h6 class="m-0 font-weight-bold text-primary">
                    <i class="fas fa-chart-pie me-2"></i>策略统计
                </h6>
            </div>
            <div class="card-body">
                <div class="mb-3">
                    <div class="small text-gray-500">总策略数</div>
                    <div class="h5 mb-0 font-weight-bold text-gray-800" id="totalStrategies">--</div>
                </div>
                <div class="mb-3">
                    <div class="small text-gray-500">运行中</div>
                    <div class="h5 mb-0 font-weight-bold text-success" id="runningStrategies">--</div>
                </div>
                <div class="mb-3">
                    <div class="small text-gray-500">已停止</div>
                    <div class="h5 mb-0 font-weight-bold text-danger" id="stoppedStrategies">--</div>
                </div>
                <div class="mb-3">
                    <div class="small text-gray-500">平均收益率</div>
                    <div class="h5 mb-0 font-weight-bold text-gray-800" id="avgReturn">--</div>
                </div>
            </div>
        </div>
        
        <!-- 快速操作 -->
        <div class="card shadow">
            <div class="card-header py-3">
                <h6 class="m-0 font-weight-bold text-primary">
                    <i class="fas fa-bolt me-2"></i>快速操作
                </h6>
            </div>
            <div class="card-body">
                <div class="d-grid gap-2">
                    <button class="btn btn-outline-success btn-sm" onclick="startAllStrategies()">
                        <i class="fas fa-play me-1"></i>启动所有策略
                    </button>
                    <button class="btn btn-outline-warning btn-sm" onclick="stopAllStrategies()">
                        <i class="fas fa-stop me-1"></i>停止所有策略
                    </button>
                    <button class="btn btn-outline-info btn-sm" onclick="refreshStrategies()">
                        <i class="fas fa-sync-alt me-1"></i>刷新状态
                    </button>
                    <button class="btn btn-outline-primary btn-sm" onclick="exportStrategies()">
                        <i class="fas fa-download me-1"></i>导出配置
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 创建策略模态框 -->
<div class="modal fade" id="createStrategyModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-plus me-2"></i>创建网格策略
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="createStrategyForm">
                    <!-- 基本信息 -->
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group mb-3">
                                <label for="strategyName">策略名称 *</label>
                                <input type="text" class="form-control" id="strategyName" name="name" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group mb-3">
                                <label for="strategyType">策略类型</label>
                                <select class="form-control" id="strategyType" name="type">
                                    <option value="grid">网格策略</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 交易设置 -->
                    <div class="row">
                        <div class="col-md-4">
                            <div class="form-group mb-3">
                                <label for="exchange">交易所 *</label>
                                <select class="form-control" id="exchange" name="exchange" required>
                                    <option value="">请选择</option>
                                    <option value="okx">OKX</option>
                                    <option value="binance">Binance</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group mb-3">
                                <label for="symbol">交易对 *</label>
                                <input type="text" class="form-control" id="symbol" name="symbol" 
                                       placeholder="BTC-USDT" required>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group mb-3">
                                <label for="tradeType">交易类型 *</label>
                                <select class="form-control" id="tradeType" name="trade_type" required>
                                    <option value="">请选择</option>
                                    <option value="spot">现货</option>
                                    <option value="futures">合约</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 网格参数 -->
                    <h6 class="text-primary mb-3">
                        <i class="fas fa-th me-2"></i>网格参数
                    </h6>
                    <div class="row">
                        <div class="col-md-4">
                            <div class="form-group mb-3">
                                <label for="gridCount">网格数量 *</label>
                                <input type="number" class="form-control" id="gridCount" name="grid_count" 
                                       min="3" max="50" value="10" required>
                                <small class="form-text text-muted">建议3-20个网格</small>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group mb-3">
                                <label for="priceMin">最低价格</label>
                                <input type="number" class="form-control" id="priceMin" name="price_min" 
                                       step="0.01" placeholder="自动计算">
                                <small class="form-text text-muted">留空自动计算</small>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group mb-3">
                                <label for="priceMax">最高价格</label>
                                <input type="number" class="form-control" id="priceMax" name="price_max" 
                                       step="0.01" placeholder="自动计算">
                                <small class="form-text text-muted">留空自动计算</small>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 资金管理 -->
                    <h6 class="text-primary mb-3">
                        <i class="fas fa-dollar-sign me-2"></i>资金管理
                    </h6>
                    <div class="row">
                        <div class="col-md-4">
                            <div class="form-group mb-3">
                                <label for="singleGridAmount">单网格金额 *</label>
                                <input type="number" class="form-control" id="singleGridAmount" 
                                       name="single_grid_amount" step="0.01" min="1" value="50" required>
                                <small class="form-text text-muted">每个网格的交易金额</small>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group mb-3">
                                <label for="stopLossRatio">止损比例</label>
                                <input type="number" class="form-control" id="stopLossRatio" 
                                       name="stop_loss_ratio" step="0.001" min="0" max="1" value="0.05">
                                <small class="form-text text-muted">0.05 = 5%</small>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group mb-3">
                                <label for="leverage">杠杆倍数</label>
                                <input type="number" class="form-control" id="leverage" name="leverage" 
                                       min="1" max="100" value="1">
                                <small class="form-text text-muted">现货固定为1</small>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 其他设置 -->
                    <h6 class="text-primary mb-3">
                        <i class="fas fa-cog me-2"></i>其他设置
                    </h6>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group mb-3">
                                <label for="interval">更新间隔</label>
                                <select class="form-control" id="interval" name="interval">
                                    <option value="1m">1分钟</option>
                                    <option value="5m" selected>5分钟</option>
                                    <option value="15m">15分钟</option>
                                    <option value="1h">1小时</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group mb-3">
                                <label for="enabled">启用状态</label>
                                <select class="form-control" id="enabled" name="enabled">
                                    <option value="true">启用</option>
                                    <option value="false">禁用</option>
                                </select>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="createStrategy()">创建策略</button>
                <button type="button" class="btn btn-info" onclick="runBacktest()">创建并回测</button>
            </div>
        </div>
    </div>
</div>

<!-- 回测结果模态框 -->
<div class="modal fade" id="backtestModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-chart-line me-2"></i>回测结果
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div id="backtestContent">
                    <div class="text-center">
                        <i class="fas fa-spinner fa-spin fa-2x text-primary"></i>
                        <p class="mt-2">回测进行中，请稍候...</p>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-success" id="deployStrategyBtn" style="display: none;" onclick="deployStrategy()">
                    <i class="fas fa-rocket me-2"></i>部署策略
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
let currentStrategyConfig = null;

$(document).ready(function() {
    // 初始化页面
    loadStrategies();
    loadStrategyStats();
    
    // 交易类型变化时更新杠杆设置
    $('#tradeType').on('change', function() {
        const leverage = $('#leverage');
        if ($(this).val() === 'spot') {
            leverage.val(1).prop('readonly', true);
        } else {
            leverage.prop('readonly', false);
        }
    });
});

// 加载策略列表
function loadStrategies() {
    $.ajax({
        url: '/api/strategies',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                updateStrategiesTable(response.data);
            }
        },
        error: function() {
            $('#strategiesBody').html('<tr><td colspan="7" class="text-center text-danger">加载失败</td></tr>');
        }
    });
}

// 更新策略表格
function updateStrategiesTable(strategies) {
    const tbody = $('#strategiesBody');
    tbody.empty();
    
    if (strategies.length === 0) {
        tbody.html('<tr><td colspan="7" class="text-center text-muted">暂无策略</td></tr>');
        return;
    }
    
    strategies.forEach(function(strategy) {
        const statusBadge = getStatusBadge(strategy.status);
        const returnClass = strategy.return_rate >= 0 ? 'text-success' : 'text-danger';
        
        const row = `
            <tr>
                <td>${strategy.name}</td>
                <td>${strategy.type}</td>
                <td>${strategy.symbol}</td>
                <td>${statusBadge}</td>
                <td class="${returnClass}">${strategy.return_rate}%</td>
                <td>${strategy.created_time}</td>
                <td>
                    <div class="btn-group" role="group">
                        <button class="btn btn-sm btn-outline-primary" onclick="viewStrategy('${strategy.id}')">
                            <i class="fas fa-eye"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-success" onclick="startStrategy('${strategy.id}')">
                            <i class="fas fa-play"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-warning" onclick="stopStrategy('${strategy.id}')">
                            <i class="fas fa-stop"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-info" onclick="backtestStrategy('${strategy.id}')">
                            <i class="fas fa-chart-line"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-danger" onclick="deleteStrategy('${strategy.id}')">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </td>
            </tr>
        `;
        tbody.append(row);
    });
}

// 获取状态徽章
function getStatusBadge(status) {
    const badges = {
        'running': '<span class="badge bg-success">运行中</span>',
        'stopped': '<span class="badge bg-danger">已停止</span>',
        'paused': '<span class="badge bg-warning">已暂停</span>',
        'error': '<span class="badge bg-danger">错误</span>'
    };
    return badges[status] || '<span class="badge bg-secondary">未知</span>';
}

// 加载策略统计
function loadStrategyStats() {
    $.ajax({
        url: '/api/strategies/stats',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                $('#totalStrategies').text(response.data.total);
                $('#runningStrategies').text(response.data.running);
                $('#stoppedStrategies').text(response.data.stopped);
                $('#avgReturn').text(response.data.avg_return + '%');
            }
        }
    });
}

// 创建策略
function createStrategy() {
    const formData = getFormData();
    if (!validateForm(formData)) {
        return;
    }
    
    $.ajax({
        url: '/api/strategies',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(formData),
        success: function(response) {
            if (response.success) {
                $('#createStrategyModal').modal('hide');
                loadStrategies();
                loadStrategyStats();
                alert('策略创建成功！');
            } else {
                alert('创建失败: ' + response.message);
            }
        },
        error: function() {
            alert('创建失败');
        }
    });
}

// 运行回测
function runBacktest() {
    const formData = getFormData();
    if (!validateForm(formData)) {
        return;
    }
    
    currentStrategyConfig = formData;
    
    // 显示回测模态框
    $('#createStrategyModal').modal('hide');
    $('#backtestModal').modal('show');
    
    // 发送回测请求
    $.ajax({
        url: '/api/backtest/run',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(formData),
        success: function(response) {
            if (response.success) {
                displayBacktestResults(response.data);
                $('#deployStrategyBtn').show();
            } else {
                $('#backtestContent').html('<div class="alert alert-danger">回测失败: ' + response.message + '</div>');
            }
        },
        error: function() {
            $('#backtestContent').html('<div class="alert alert-danger">回测失败</div>');
        }
    });
}

// 显示回测结果
function displayBacktestResults(results) {
    const content = `
        <div class="row">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h6 class="m-0 font-weight-bold text-primary">回测统计</h6>
                    </div>
                    <div class="card-body">
                        <table class="table table-sm">
                            <tr><td>总收益率</td><td class="${results.total_return >= 0 ? 'text-success' : 'text-danger'}">${results.total_return}%</td></tr>
                            <tr><td>总交易次数</td><td>${results.total_trades}</td></tr>
                            <tr><td>获胜交易</td><td>${results.winning_trades}</td></tr>
                            <tr><td>胜率</td><td>${results.win_rate}%</td></tr>
                            <tr><td>最大回撤</td><td class="text-danger">${results.max_drawdown}%</td></tr>
                            <tr><td>夏普比率</td><td>${results.sharpe_ratio}</td></tr>
                            <tr><td>总盈亏</td><td class="${results.total_pnl >= 0 ? 'text-success' : 'text-danger'}">${results.total_pnl} USDT</td></tr>
                        </table>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h6 class="m-0 font-weight-bold text-primary">策略评估</h6>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <div class="small text-gray-500">策略评分</div>
                            <div class="h4 mb-0 font-weight-bold ${getScoreColor(results.score)}">${results.score}/100</div>
                        </div>
                        <div class="mb-3">
                            <div class="small text-gray-500">风险等级</div>
                            <div class="h6 mb-0">${getRiskLevel(results.risk_level)}</div>
                        </div>
                        <div class="mb-3">
                            <div class="small text-gray-500">建议</div>
                            <div class="small">${results.recommendation}</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="mt-4">
            <h6 class="text-primary">最近交易记录</h6>
            <div class="table-responsive">
                <table class="table table-sm">
                    <thead>
                        <tr>
                            <th>时间</th>
                            <th>方向</th>
                            <th>价格</th>
                            <th>数量</th>
                            <th>盈亏</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${results.recent_trades.map(trade => `
                            <tr>
                                <td>${trade.timestamp}</td>
                                <td><span class="badge ${trade.side === 'buy' ? 'bg-success' : 'bg-danger'}">${trade.side}</span></td>
                                <td>${trade.price}</td>
                                <td>${trade.quantity}</td>
                                <td class="${trade.pnl >= 0 ? 'text-success' : 'text-danger'}">${trade.pnl}</td>
                            </tr>
                        `).join('')}
                    </tbody>
                </table>
            </div>
        </div>
    `;
    
    $('#backtestContent').html(content);
}

// 获取评分颜色
function getScoreColor(score) {
    if (score >= 80) return 'text-success';
    if (score >= 60) return 'text-warning';
    return 'text-danger';
}

// 获取风险等级
function getRiskLevel(level) {
    const levels = {
        'low': '<span class="badge bg-success">低风险</span>',
        'medium': '<span class="badge bg-warning">中风险</span>',
        'high': '<span class="badge bg-danger">高风险</span>'
    };
    return levels[level] || '<span class="badge bg-secondary">未知</span>';
}

// 部署策略
function deployStrategy() {
    if (!currentStrategyConfig) {
        alert('策略配置丢失');
        return;
    }
    
    $.ajax({
        url: '/api/strategies',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(currentStrategyConfig),
        success: function(response) {
            if (response.success) {
                $('#backtestModal').modal('hide');
                loadStrategies();
                loadStrategyStats();
                alert('策略部署成功！');
            } else {
                alert('部署失败: ' + response.message);
            }
        },
        error: function() {
            alert('部署失败');
        }
    });
}

// 获取表单数据
function getFormData() {
    return {
        name: $('#strategyName').val(),
        type: $('#strategyType').val(),
        exchange: $('#exchange').val(),
        symbol: $('#symbol').val(),
        trade_type: $('#tradeType').val(),
        grid_count: parseInt($('#gridCount').val()),
        price_min: parseFloat($('#priceMin').val()) || 0,
        price_max: parseFloat($('#priceMax').val()) || 0,
        single_grid_amount: parseFloat($('#singleGridAmount').val()),
        stop_loss_ratio: parseFloat($('#stopLossRatio').val()) || 0,
        leverage: parseInt($('#leverage').val()),
        interval: $('#interval').val(),
        enabled: $('#enabled').val() === 'true'
    };
}

// 验证表单
function validateForm(data) {
    if (!data.name || !data.exchange || !data.symbol || !data.trade_type) {
        alert('请填写必填字段');
        return false;
    }
    
    if (data.grid_count < 3 || data.grid_count > 50) {
        alert('网格数量必须在3-50之间');
        return false;
    }
    
    if (data.single_grid_amount <= 0) {
        alert('单网格金额必须大于0');
        return false;
    }
    
    return true;
}

// 策略操作函数
function viewStrategy(id) {
    window.open('/strategies/' + id, '_blank');
}

function startStrategy(id) {
    $.ajax({
        url: '/api/strategies/' + id + '/start',
        method: 'POST',
        success: function(response) {
            if (response.success) {
                loadStrategies();
                alert('策略启动成功');
            } else {
                alert('启动失败: ' + response.message);
            }
        }
    });
}

function stopStrategy(id) {
    $.ajax({
        url: '/api/strategies/' + id + '/stop',
        method: 'POST',
        success: function(response) {
            if (response.success) {
                loadStrategies();
                alert('策略停止成功');
            } else {
                alert('停止失败: ' + response.message);
            }
        }
    });
}

function backtestStrategy(id) {
    // 实现策略回测
    alert('回测功能开发中...');
}

function deleteStrategy(id) {
    if (confirm('确定要删除这个策略吗？')) {
        $.ajax({
            url: '/api/strategies/' + id,
            method: 'DELETE',
            success: function(response) {
                if (response.success) {
                    loadStrategies();
                    loadStrategyStats();
                    alert('策略删除成功');
                } else {
                    alert('删除失败: ' + response.message);
                }
            }
        });
    }
}

// 批量操作
function startAllStrategies() {
    if (confirm('确定要启动所有策略吗？')) {
        $.ajax({
            url: '/api/strategies/start-all',
            method: 'POST',
            success: function(response) {
                loadStrategies();
                alert('批量启动完成');
            }
        });
    }
}

function stopAllStrategies() {
    if (confirm('确定要停止所有策略吗？')) {
        $.ajax({
            url: '/api/strategies/stop-all',
            method: 'POST',
            success: function(response) {
                loadStrategies();
                alert('批量停止完成');
            }
        });
    }
}

function refreshStrategies() {
    loadStrategies();
    loadStrategyStats();
}

function exportStrategies() {
    window.open('/api/strategies/export', '_blank');
}
</script>
{% endblock %}